package com.innovation.ic.im.end.web.thread;

import com.alibaba.fastjson.JSON;
import com.innovation.ic.b1b.framework.manager.ThreadPoolManager;
import com.innovation.ic.im.end.base.model.im_erp9.GroupMessage;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.service.helper.ServiceImplHelper;
import com.innovation.ic.im.end.base.service.im_erp9.RefGroupAccountService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.thread.web.SaveRetractionGroupMessageReceiverThread;
import com.innovation.ic.im.end.base.vo.im_erp9.SendGroupMessageVo;
import com.innovation.ic.im.end.web.endpoint.GroupEndpoint;
import lombok.SneakyThrows;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import javax.websocket.Session;
import java.util.*;

/**
 * @desc   保存默认群组撤回消息对象内容
 * @author linuo
 * @time   2022年8月9日14:39:53
 */
public class SaveRetractionGroupMessageThread extends AbstractThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String exchange;

    private Map<String, Set<GroupEndpoint>> onlineGroupMap;

    private Long waitingLockTime;

    public SaveRetractionGroupMessageThread(GroupMessage groupMessage, Map<String, Set<GroupEndpoint>> onlineGroupMap,
                                            String exchange, CuratorFramework curatorFramework, Long waitingLockTime,
                                            ThreadPoolManager threadPoolManager) {
        this.groupMessage = groupMessage;
        this.onlineGroupMap = onlineGroupMap;
        this.exchange = exchange;
        this.curatorFramework = curatorFramework;
        this.waitingLockTime = waitingLockTime;
        this.threadPoolManager = threadPoolManager;
    }

    public SaveRetractionGroupMessageThread() {}

    @SneakyThrows
    @Override
    public void run() {
        // 更新最近联系时间
        RefGroupAccountService refGroupAccountService = ServiceImplHelper.getRefGroupAccountService();
        refGroupAccountService.updateLastContactTimeByGroupId(groupMessage.getGroupId());

        // 保存群组消息获取消息id
        ServiceResult<Integer> insertGroupMsgResult = ServiceImplHelper.getGroupMessageService().saveGroupMessage(this.groupMessage);
        Integer groupMessageId = insertGroupMsgResult.getResult();
        groupMessage.setId(groupMessageId);

        // 处理账号和群组的操作表数据
        ServiceImplHelper.getRefGroupAccountOperationService().handleRefGroupAccountOperationData(groupMessage.getGroupId(), groupMessage.getFromUserAccount(), curatorFramework, waitingLockTime);

        // 保存群组未读消息数据
        SaveRetractionGroupMessageReceiverThread saveRetractionGroupMessageReceiverThread = new SaveRetractionGroupMessageReceiverThread(exchange, waitingLockTime, groupMessageId, groupMessage, curatorFramework);
        threadPoolManager.execute(saveRetractionGroupMessageReceiverThread);

        // 将消息发送给群组中每一个在线的用户,包括自己
        Set<GroupEndpoint> groupEndpointSet = onlineGroupMap.get(groupMessage.getGroupId());
        if(groupEndpointSet != null && groupEndpointSet.size() > 0){
            for (GroupEndpoint groupEndpoint : groupEndpointSet) {
                Session theSession = groupEndpoint.session;
                synchronized (theSession) {
                    if (theSession.isOpen()) {
                        SendGroupMessageVo sendGroupMessageVo = new SendGroupMessageVo();
                        BeanUtils.copyProperties(groupMessage, sendGroupMessageVo);
                        logger.info("sendGroupMessageVo=[{}]", sendGroupMessageVo);
                        theSession.getAsyncRemote().sendText(JSON.toJSONString(sendGroupMessageVo));
                    }
                }

                logger.info("用户【" + groupMessage.getFromUserAccount() + "】向群组【"
                        + groupMessage.getGroupId() + "】中的用户【" + groupEndpoint.account
                        + "】发送系统消息【" + groupMessage.getContent() + "】");
            }
        }
    }
}